package com.aidong.util;

import javax.servlet.http.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


public class CookieUtil {
	private static String defaultDomain = null;

	public CookieUtil() {
	}

	public static String getCookie(HttpServletRequest request, String cookieName) {
		if(null != cookieName && !"".equals(cookieName)) {
			Cookie[] cookies = request.getCookies();
			if(cookies != null && cookies.length > 0) {
				Cookie[] arr$ = cookies;
				int len$ = cookies.length;

				for(int i$ = 0; i$ < len$; ++i$) {
					Cookie cookie = arr$[i$];
					if(cookieName.equals(cookie.getName())) {
						try {
							return URLDecoder.decode(cookie.getValue(), "utf-8");
						} catch (UnsupportedEncodingException var8) {
							System.err.println(var8.getClass().getName() + ": " + var8.getMessage());
						}
					}
				}
			}

			return null;
		} else {
			return null;
		}
	}

	public static void setCookie(HttpServletResponse response, String cookieName, String cookieValue) {
		setCookie(response, defaultDomain, cookieName, cookieValue);
	}

	public static void setCookie(HttpServletResponse response, String domain, String cookieName, String cookieValue) {
		String path = "/";
		byte validTime = -1;
		setCookie(response, cookieName, cookieValue, path, validTime, domain);
	}

	public static void setCookie(HttpServletResponse response, String cookieName, String cookieValue, String path, int validTime, String domain) {
		try {
			Cookie e = new Cookie(cookieName, cookieValue == null?null: URLEncoder.encode(cookieValue, "utf-8"));
			e.setPath(path);
			e.setMaxAge(validTime);
			if(null != domain) {
				e.setDomain(domain);
			}

			response.addCookie(e);
		} catch (UnsupportedEncodingException var7) {
			System.err.println(var7.getClass().getName() + ": " + var7.getMessage());
		}

	}

	public static void removeCookies(HttpServletResponse response, String cookieName) {
		removeCookies(response, defaultDomain, cookieName);
	}

	public static void removeCookies(HttpServletResponse response, String domain, String cookieName) {
		String path = "/";
		byte validTime = 0;
		setCookie(response, cookieName, (String)null, path, validTime, domain);
	}
}
